//
//  NewfeatureViewController.swift
//  sinaWeibo
//
//  Created by 张国梁 on 16/4/11.
//  Copyright © 2016年 CoderGL. All rights reserved.
//

import UIKit

private let identifier = "identifier"
private let numbersOfItems = 4

class NewfeatureViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(collectionView)
        view.addSubview(pageControl)
    }
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        pageControl.xmg_AlignInner(type: XMG_AlignType.BottomCenter, referView: view, size: nil, offset: CGPointMake(0, -50))
    }
    
    private lazy var pageControl : UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.numberOfPages = numbersOfItems
        pageControl.hidesForSinglePage = true
        pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
        pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
        pageControl.sizeToFit()
        return pageControl
    }()
    
    private lazy var collectionView : UICollectionView = {
       let collectionView = UICollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: NewfeatureLayout())
        collectionView.backgroundColor = UIColor.redColor()
        collectionView.dataSource = self
        collectionView.delegate = self
        
        collectionView.registerClass(NewfeatureCell.self, forCellWithReuseIdentifier: identifier)
        return collectionView
    }()
}

extension NewfeatureViewController : UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return numbersOfItems
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 创建cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! NewfeatureCell
        // 返回cell
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        // 给cell绑定数据
        let newfeatureCell = cell as! NewfeatureCell
        newfeatureCell.imageIndex = indexPath.row;
    }
    
    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        let currentPath = collectionView.indexPathsForVisibleItems().last!
        
        // 设置pageControl页码
        pageControl.currentPage = currentPath.item
        
        if currentPath.item == numbersOfItems-1 { // 最后一页才需要执行动画
            let newfeatureCell = collectionView.cellForItemAtIndexPath(currentPath) as! NewfeatureCell
            newfeatureCell.startBtnStartAnimation()
        }
    }
}

class NewfeatureCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI(){
        contentView.addSubview(imageView)
        contentView.addSubview(startBtn)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        //        imageView.frame = contentView.bounds
        imageView.xmg_Fill(contentView)
        startBtn.xmg_AlignInner(type: XMG_AlignType.BottomCenter, referView: contentView, size:nil, offset: CGPointMake(0, -150))
    }
    
    func startBtnStartAnimation() {
        startBtn.transform = CGAffineTransformMakeScale(0, 0)
        startBtn.userInteractionEnabled = false
        UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
                self.startBtn.transform = CGAffineTransformIdentity
            }) { (_) in
                self.startBtn.userInteractionEnabled = true
        }
    }
    
    func startBtnClick() {
        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerKey, object: true)
        print(#function)
    }
    
    private var imageIndex : Int? {
        didSet{
            imageView.image = UIImage(named: "new_feature_\(imageIndex! + 1)")
            startBtn.hidden = imageIndex == numbersOfItems-1 ? false : true
        }
    }
    private lazy var imageView = UIImageView()
    
    
    private lazy var startBtn : UIButton = {
       let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "new_feature_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_button_highlighted"), forState: UIControlState.Highlighted)
        btn.addTarget(self, action: #selector(NewfeatureCell.startBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
        btn.sizeToFit()
        return btn
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



private class NewfeatureLayout : UICollectionViewFlowLayout {
    private override func prepareLayout() {
        super.prepareLayout()
        
        // 布局属性
        itemSize = (collectionView?.bounds.size)!
        minimumLineSpacing = 0.0
        minimumInteritemSpacing = 0.0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // collectionView属性 
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}